package com.heima.gateway.filter;

import cn.hutool.core.text.AntPathMatcher;
import com.heima.gateway.config.ExcludePaths;
import com.heima.gateway.utils.JwtTool;
import com.hmall.common.exception.UnauthorizedException;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
@Component
@RequiredArgsConstructor
public class AuthFilter implements GlobalFilter, Ordered {
    private final ExcludePaths excludePaths;

    private final JwtTool jwtTool;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher() ;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
//        1.判断请求路径是否在排除列表中
        System.out.println("Path:" + request.getPath().toString());
        if (isExclude(request.getPath().toString())){
            return chain.filter(exchange); //放行
        }
        System.out.println("------"+ isExclude(request.getPath().toString())+ "--------");
//        2.获取token
        String token = null;
        List<String> headers = request.getHeaders().get("authorization");
        System.out.println("token:" + headers);
        if (headers != null && headers.size() > 0){
            token = headers.get(0);
        }
//        3.解析token
        Long userId;
        try {
            userId = jwtTool.parseToken(token);
            System.out.println(userId == null ? null : userId);
        } catch (UnauthorizedException e) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        System.out.println("userId:" + userId);
//        4.传递用户信息
        String userInfo = userId.toString();
        ServerWebExchange swe = exchange
                .mutate()
                .request(builder -> builder.header("user-info",userInfo))
                .build();

        System.out.println("userInfo:" +userInfo);
        return chain.filter(swe); //放行

    }

    public boolean isExclude(String path){
        for (String excludePath : excludePaths.getExcludePaths()) {
            if (antPathMatcher.match(excludePath,path)){
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
